package com.summer.utils;

import java.io.FileReader;
import java.util.List;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

/**
 * @todo : 系统配置文件读取辅助类
 */
public class PropertiesConfig {
	private Logger log = Logger.getLogger(PropertiesConfig.class);
	private Properties prop = new Properties();
	private boolean isLoad = false;
	private String path;

	public void setFilepath(String path) {
		this.path = path;
	}

	public PropertiesConfig(String filepath) {
		load(filepath);
	}

	public void load(String path) {
		if (StringUtils.isEmpty(StringUtils.trim(path))) {
			log.debug("配置文件路径信息为null");
			return;
		}
		try {
			this.path = path;
			prop.load(new FileReader(path));
			isLoad = true;
		} catch (Exception e) {
			log.error("找不到配置文件.");
			return;
		}
	}

	public void reload() {
		if (StringUtils.isEmpty(StringUtils.trim(this.path))) {
			log.debug("重读配置失败，配置路径不正确");
			return;
		}
		prop.clear();
		load(this.path);
	}

	public String getString(String key) {
		ensureLoaded();
		return prop.getProperty(key);
	}

	
	public List<String> getList(String key){
		return ListStringUtils.getList(prop.getProperty(key));
	}
	

	public int getInt(String key) {
		ensureLoaded();
		String temp = prop.getProperty(key);
		int value = 0;
		try {
			value = Integer.parseInt(temp);
		} catch (Exception e) {
			log.error("配置文件读取整数失败..key为" + key + " value 为" + temp);
			throw e; // 为了防止读取到错误数据，此处抛出异常
		}
		return value;
	}

	private void ensureLoaded() {
		if (!this.isLoad) {
			throw new RuntimeException("请先正确加载配置文件");
		}
	}
}
